<template>
  <div class="message-management">
    <!-- 消息概览 -->
    <el-row :gutter="20" class="message-overview">
      <el-col :span="6" v-for="stat in messageStats" :key="stat.key">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" :class="stat.type">
              <el-icon><component :is="stat.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-label">{{ stat.label }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 消息管理标签页 -->
    <el-tabs v-model="activeTab" class="message-tabs">
      <!-- 消息列表 -->
      <el-tab-pane label="消息列表" name="list">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-input
                  v-model="searchQuery"
                  placeholder="搜索消息"
                  style="width: 200px"
                  clearable
                  @clear="handleSearch"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
                <el-select v-model="messageType" placeholder="消息类型" clearable @change="handleSearch">
                  <el-option label="系统通知" value="system" />
                  <el-option label="告警通知" value="alert" />
                  <el-option label="业务通知" value="business" />
                </el-select>
                <el-select v-model="messageStatus" placeholder="消息状态" clearable @change="handleSearch">
                  <el-option label="未读" value="unread" />
                  <el-option label="已读" value="read" />
                  <el-option label="已处理" value="processed" />
                </el-select>
              </div>
              <div class="header-right">
                <el-button type="primary" @click="handleSendMessage">发送消息</el-button>
                <el-button @click="handleBatchRead">批量标记已读</el-button>
                <el-button @click="handleBatchDelete">批量删除</el-button>
              </div>
            </div>
          </template>

          <el-table
            :data="messageList"
            border
            v-loading="tableLoading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="title" label="标题" min-width="200" />
            <el-table-column prop="type" label="类型" width="100">
              <template #default="{ row }">
                <el-tag :type="getMessageTypeTag(row.type)">{{ getMessageTypeLabel(row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getMessageStatusTag(row.status)">{{ getMessageStatusLabel(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sender" label="发送者" width="120" />
            <el-table-column prop="createTime" label="发送时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleViewMessage(row)">查看</el-button>
                <el-button link type="primary" @click="handleMarkRead(row)" v-if="row.status === 'unread'">
                  标记已读
                </el-button>
                <el-button link type="danger" @click="handleDeleteMessage(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-tab-pane>

      <!-- 消息模板 -->
      <el-tab-pane label="消息模板" name="template">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-input
                  v-model="templateSearch"
                  placeholder="搜索模板"
                  style="width: 200px"
                  clearable
                  @clear="handleTemplateSearch"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
                <el-select v-model="templateType" placeholder="模板类型" clearable @change="handleTemplateSearch">
                  <el-option label="系统通知" value="system" />
                  <el-option label="告警通知" value="alert" />
                  <el-option label="业务通知" value="business" />
                </el-select>
              </div>
              <div class="header-right">
                <el-button type="primary" @click="handleCreateTemplate">创建模板</el-button>
              </div>
            </div>
          </template>

          <el-table :data="templateList" border v-loading="templateLoading">
            <el-table-column prop="name" label="模板名称" min-width="150" />
            <el-table-column prop="type" label="类型" width="100">
              <template #default="{ row }">
                <el-tag :type="getMessageTypeTag(row.type)">{{ getMessageTypeLabel(row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" min-width="200" />
            <el-table-column prop="updateTime" label="更新时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.updateTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleEditTemplate(row)">编辑</el-button>
                <el-button link type="primary" @click="handlePreviewTemplate(row)">预览</el-button>
                <el-button link type="danger" @click="handleDeleteTemplate(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>

      <!-- 发送记录 -->
      <el-tab-pane label="发送记录" name="record">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-input
                  v-model="recordSearch"
                  placeholder="搜索记录"
                  style="width: 200px"
                  clearable
                  @clear="handleRecordSearch"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
                <el-select v-model="recordType" placeholder="记录类型" clearable @change="handleRecordSearch">
                  <el-option label="系统通知" value="system" />
                  <el-option label="告警通知" value="alert" />
                  <el-option label="业务通知" value="business" />
                </el-select>
                <el-date-picker
                  v-model="recordTimeRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="handleRecordSearch"
                />
              </div>
              <div class="header-right">
                <el-button @click="handleExportRecords">导出记录</el-button>
              </div>
            </div>
          </template>

          <el-table :data="recordList" border v-loading="recordLoading">
            <el-table-column prop="title" label="消息标题" min-width="200" />
            <el-table-column prop="type" label="类型" width="100">
              <template #default="{ row }">
                <el-tag :type="getMessageTypeTag(row.type)">{{ getMessageTypeLabel(row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="receiver" label="接收者" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getMessageStatusTag(row.status)">{{ getMessageStatusLabel(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="sendTime" label="发送时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.sendTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="readTime" label="阅读时间" width="180">
              <template #default="{ row }">
                {{ row.readTime ? formatDateTime(row.readTime) : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" @click="handleViewRecord(row)">查看</el-button>
                <el-button link type="danger" @click="handleDeleteRecord(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="recordPage"
              v-model:page-size="recordPageSize"
              :total="recordTotal"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleRecordSizeChange"
              @current-change="handleRecordPageChange"
            />
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="messageDialogVisible"
      :title="messageDialogTitle"
      width="600px"
      destroy-on-close
    >
      <div class="message-detail">
        <div class="message-header">
          <h3>{{ currentMessage.title }}</h3>
          <div class="message-meta">
            <el-tag :type="getMessageTypeTag(currentMessage.type)">
              {{ getMessageTypeLabel(currentMessage.type) }}
            </el-tag>
            <span class="sender">发送者：{{ currentMessage.sender }}</span>
            <span class="time">发送时间：{{ formatDateTime(currentMessage.createTime) }}</span>
          </div>
        </div>
        <div class="message-content" v-html="currentMessage.content"></div>
        <div class="message-attachments" v-if="currentMessage.attachments?.length">
          <h4>附件</h4>
          <ul>
            <li v-for="file in currentMessage.attachments" :key="file.id">
              <el-link type="primary" @click="handleDownloadAttachment(file)">
                {{ file.name }}
              </el-link>
            </li>
          </ul>
        </div>
      </div>
    </el-dialog>

    <!-- 消息模板对话框 -->
    <el-dialog
      v-model="templateDialogVisible"
      :title="templateDialogTitle"
      width="800px"
      destroy-on-close
    >
      <el-form
        ref="templateFormRef"
        :model="templateForm"
        :rules="templateRules"
        label-width="100px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="templateForm.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板类型" prop="type">
          <el-select v-model="templateForm.type" placeholder="请选择模板类型">
            <el-option label="系统通知" value="system" />
            <el-option label="告警通知" value="alert" />
            <el-option label="业务通知" value="business" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板描述" prop="description">
          <el-input
            v-model="templateForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入模板描述"
          />
        </el-form-item>
        <el-form-item label="模板内容" prop="content">
          <el-input
            v-model="templateForm.content"
            type="textarea"
            rows="10"
            placeholder="请输入模板内容，支持HTML格式"
          />
        </el-form-item>
        <el-form-item label="变量说明" prop="variables">
          <el-input
            v-model="templateForm.variables"
            type="textarea"
            rows="3"
            placeholder="请输入变量说明，每行一个变量"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="templateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveTemplate">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Bell,
  Message,
  Document,
  Clock,
  Search,
  Download
} from '@element-plus/icons-vue'
import {
  getMessageList,
  getMessageTemplateList,
  getMessageRecordList,
  createMessageTemplate,
  updateMessageTemplate,
  deleteMessageTemplate,
  sendMessage,
  markMessageRead,
  deleteMessage,
  exportMessageRecords
} from '@/api/message'

// 消息统计数据
const messageStats = reactive([
  {
    key: 'total',
    label: '消息总数',
    value: 0,
    type: 'primary',
    icon: 'Bell'
  },
  {
    key: 'unread',
    label: '未读消息',
    value: 0,
    type: 'warning',
    icon: 'Message'
  },
  {
    key: 'template',
    label: '消息模板',
    value: 0,
    type: 'success',
    icon: 'Document'
  },
  {
    key: 'today',
    label: '今日发送',
    value: 0,
    type: 'info',
    icon: 'Clock'
  }
])

// 标签页
const activeTab = ref('list')

// 消息列表
const messageList = ref([])
const tableLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const searchQuery = ref('')
const messageType = ref('')
const messageStatus = ref('')
const selectedMessages = ref([])

// 消息模板
const templateList = ref([])
const templateLoading = ref(false)
const templateSearch = ref('')
const templateType = ref('')

// 发送记录
const recordList = ref([])
const recordLoading = ref(false)
const recordPage = ref(1)
const recordPageSize = ref(20)
const recordTotal = ref(0)
const recordSearch = ref('')
const recordType = ref('')
const recordTimeRange = ref([])

// 对话框
const messageDialogVisible = ref(false)
const messageDialogTitle = ref('')
const currentMessage = ref({})
const templateDialogVisible = ref(false)
const templateDialogTitle = ref('')
const templateFormRef = ref(null)
const templateForm = reactive({
  id: '',
  name: '',
  type: '',
  description: '',
  content: '',
  variables: ''
})

// 表单验证规则
const templateRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择模板类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入模板内容', trigger: 'blur' }
  ]
}

// 初始化
onMounted(() => {
  loadMessageStats()
  loadMessageList()
  loadTemplateList()
  loadRecordList()
})

// 加载消息统计
const loadMessageStats = async () => {
  try {
    const res = await getMessageList({ type: 'stats' })
    messageStats.forEach(stat => {
      stat.value = res.data[stat.key] || 0
    })
  } catch (error) {
    console.error('加载消息统计失败:', error)
    ElMessage.error('加载消息统计失败')
  }
}

// 加载消息列表
const loadMessageList = async () => {
  try {
    tableLoading.value = true
    const res = await getMessageList({
      page: currentPage.value,
      pageSize: pageSize.value,
      search: searchQuery.value,
      type: messageType.value,
      status: messageStatus.value
    })
    messageList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('加载消息列表失败:', error)
    ElMessage.error('加载消息列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 加载模板列表
const loadTemplateList = async () => {
  try {
    templateLoading.value = true
    const res = await getMessageTemplateList({
      search: templateSearch.value,
      type: templateType.value
    })
    templateList.value = res.data
  } catch (error) {
    console.error('加载模板列表失败:', error)
    ElMessage.error('加载模板列表失败')
  } finally {
    templateLoading.value = false
  }
}

// 加载发送记录
const loadRecordList = async () => {
  try {
    recordLoading.value = true
    const res = await getMessageRecordList({
      page: recordPage.value,
      pageSize: recordPageSize.value,
      search: recordSearch.value,
      type: recordType.value,
      startTime: recordTimeRange.value?.[0],
      endTime: recordTimeRange.value?.[1]
    })
    recordList.value = res.data.list
    recordTotal.value = res.data.total
  } catch (error) {
    console.error('加载发送记录失败:', error)
    ElMessage.error('加载发送记录失败')
  } finally {
    recordLoading.value = false
  }
}

// 工具方法
const getMessageTypeTag = (type) => {
  const typeMap = {
    system: 'info',
    alert: 'danger',
    business: 'success'
  }
  return typeMap[type] || 'info'
}

const getMessageTypeLabel = (type) => {
  const labelMap = {
    system: '系统通知',
    alert: '告警通知',
    business: '业务通知'
  }
  return labelMap[type] || type
}

const getMessageStatusTag = (status) => {
  const statusMap = {
    unread: 'warning',
    read: 'success',
    processed: 'info'
  }
  return statusMap[status] || 'info'
}

const getMessageStatusLabel = (status) => {
  const labelMap = {
    unread: '未读',
    read: '已读',
    processed: '已处理'
  }
  return labelMap[status] || status
}

const formatDateTime = (timestamp) => {
  return new Date(timestamp).toLocaleString()
}

// 事件处理
const handleSearch = () => {
  currentPage.value = 1
  loadMessageList()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadMessageList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadMessageList()
}

const handleSelectionChange = (selection) => {
  selectedMessages.value = selection
}

const handleViewMessage = (message) => {
  currentMessage.value = message
  messageDialogTitle.value = '消息详情'
  messageDialogVisible.value = true
  if (message.status === 'unread') {
    handleMarkRead(message)
  }
}

const handleMarkRead = async (message) => {
  try {
    await markMessageRead(message.id)
    ElMessage.success('标记已读成功')
    loadMessageList()
    loadMessageStats()
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('标记已读失败')
  }
}

const handleDeleteMessage = async (message) => {
  try {
    await ElMessageBox.confirm('确定要删除该消息吗？', '提示', {
      type: 'warning'
    })
    await deleteMessage(message.id)
    ElMessage.success('删除成功')
    loadMessageList()
    loadMessageStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除消息失败:', error)
      ElMessage.error('删除消息失败')
    }
  }
}

const handleBatchRead = async () => {
  if (!selectedMessages.value.length) {
    ElMessage.warning('请选择要标记的消息')
    return
  }
  try {
    await Promise.all(
      selectedMessages.value.map(message => markMessageRead(message.id))
    )
    ElMessage.success('批量标记已读成功')
    loadMessageList()
    loadMessageStats()
  } catch (error) {
    console.error('批量标记已读失败:', error)
    ElMessage.error('批量标记已读失败')
  }
}

const handleBatchDelete = async () => {
  if (!selectedMessages.value.length) {
    ElMessage.warning('请选择要删除的消息')
    return
  }
  try {
    await ElMessageBox.confirm('确定要删除选中的消息吗？', '提示', {
      type: 'warning'
    })
    await Promise.all(
      selectedMessages.value.map(message => deleteMessage(message.id))
    )
    ElMessage.success('批量删除成功')
    loadMessageList()
    loadMessageStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

const handleTemplateSearch = () => {
  loadTemplateList()
}

const handleCreateTemplate = () => {
  templateDialogTitle.value = '创建模板'
  templateForm.id = ''
  templateForm.name = ''
  templateForm.type = ''
  templateForm.description = ''
  templateForm.content = ''
  templateForm.variables = ''
  templateDialogVisible.value = true
}

const handleEditTemplate = (template) => {
  templateDialogTitle.value = '编辑模板'
  Object.assign(templateForm, template)
  templateDialogVisible.value = true
}

const handlePreviewTemplate = (template) => {
  currentMessage.value = {
    title: template.name,
    content: template.content,
    type: template.type,
    sender: '系统',
    createTime: new Date().toISOString()
  }
  messageDialogTitle.value = '模板预览'
  messageDialogVisible.value = true
}

const handleDeleteTemplate = async (template) => {
  try {
    await ElMessageBox.confirm('确定要删除该模板吗？', '提示', {
      type: 'warning'
    })
    await deleteMessageTemplate(template.id)
    ElMessage.success('删除成功')
    loadTemplateList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除模板失败:', error)
      ElMessage.error('删除模板失败')
    }
  }
}

const handleSaveTemplate = async () => {
  if (!templateFormRef.value) return
  try {
    await templateFormRef.value.validate()
    if (templateForm.id) {
      await updateMessageTemplate(templateForm)
      ElMessage.success('更新成功')
    } else {
      await createMessageTemplate(templateForm)
      ElMessage.success('创建成功')
    }
    templateDialogVisible.value = false
    loadTemplateList()
  } catch (error) {
    console.error('保存模板失败:', error)
    ElMessage.error('保存模板失败')
  }
}

const handleRecordSearch = () => {
  recordPage.value = 1
  loadRecordList()
}

const handleRecordSizeChange = (val) => {
  recordPageSize.value = val
  loadRecordList()
}

const handleRecordPageChange = (val) => {
  recordPage.value = val
  loadRecordList()
}

const handleViewRecord = (record) => {
  currentMessage.value = record
  messageDialogTitle.value = '发送记录详情'
  messageDialogVisible.value = true
}

const handleDeleteRecord = async (record) => {
  try {
    await ElMessageBox.confirm('确定要删除该记录吗？', '提示', {
      type: 'warning'
    })
    await deleteMessage(record.id)
    ElMessage.success('删除成功')
    loadRecordList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除记录失败:', error)
      ElMessage.error('删除记录失败')
    }
  }
}

const handleExportRecords = async () => {
  try {
    const res = await exportMessageRecords({
      search: recordSearch.value,
      type: recordType.value,
      startTime: recordTimeRange.value?.[0],
      endTime: recordTimeRange.value?.[1]
    })
    
    const blob = new Blob([res.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `消息发送记录_${new Date().getTime()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('导出记录失败:', error)
    ElMessage.error('导出记录失败')
  }
}

const handleDownloadAttachment = async (file) => {
  try {
    const res = await downloadAttachment(file.id)
    const blob = new Blob([res.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = file.name
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('下载附件失败:', error)
    ElMessage.error('下载附件失败')
  }
}
</script>

<style lang="scss" scoped>
.message-management {
  padding: 20px;
  
  .message-overview {
    margin-bottom: 20px;
    
    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        gap: 20px;
        
        .stat-icon {
          width: 48px;
          height: 48px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24px;
          
          &.primary {
            background-color: #ecf5ff;
            color: #409eff;
          }
          
          &.warning {
            background-color: #fdf6ec;
            color: #e6a23c;
          }
          
          &.success {
            background-color: #f0f9eb;
            color: #67c23a;
          }
          
          &.info {
            background-color: #f4f4f5;
            color: #909399;
          }
        }
        
        .stat-info {
          .stat-value {
            font-size: 24px;
            font-weight: bold;
            line-height: 1;
            margin-bottom: 8px;
          }
          
          .stat-label {
            color: #909399;
            font-size: 14px;
          }
        }
      }
    }
  }
  
  .message-tabs {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      .header-left {
        display: flex;
        align-items: center;
        gap: 10px;
      }
      
      .header-right {
        display: flex;
        align-items: center;
        gap: 10px;
      }
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  
  .message-detail {
    .message-header {
      margin-bottom: 20px;
      
      h3 {
        margin: 0 0 10px;
        font-size: 18px;
      }
      
      .message-meta {
        display: flex;
        align-items: center;
        gap: 20px;
        color: #909399;
        font-size: 14px;
      }
    }
    
    .message-content {
      margin-bottom: 20px;
      line-height: 1.6;
    }
    
    .message-attachments {
      h4 {
        margin: 0 0 10px;
        font-size: 16px;
      }
      
      ul {
        margin: 0;
        padding: 0;
        list-style: none;
        
        li {
          margin-bottom: 8px;
          
          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}
</style> 